
import React, { createRef } from 'react'
import { http, IUdFormItem, UdForm, validators, UdToolbar, UdModal } from '@/lib'
import { Input, Select, InputNumber, message, Button } from 'antd'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import AddMaterialModal from './AddMaterialModal'
import apis from '@/apis/AboutQuota'
import './approve.scss'

const { TextArea } = Input
interface IProps {
  stockForm: any
  handQuery?: any
}
interface IState {
  stockForm: any
  nowMove: null | number
}
export default class AddCheckStockDetail extends React.Component<IProps, IState> {
  private stockForm = { ...this.props.stockForm }
  labelCol: any = { span: 4 }
  private wrapperCol: any = { span: 20 }
  private form: WrappedFormUtils
  public cRef = createRef<any>()

  state = {
    record: {},
    stockForm: {},
    nowMove: null,
  }

  componentDidMount() { }

  private onOk = e => {
    this.form.validateFields((err, values) => {
      if (!err) {
        let { matName } = values;
        let { stockForm } = this.props
        values.prodBarcode = matName.prodBarcode;
        values.matName = matName.matName;
        values.brandName = values.brandNameShort.split(" ")[0];
        values.dealerName = values.dealerName.split(" ")[0];
        stockForm["inventoryBegineTime"] = stockForm.inventoryTime[0].format('yyyy-MM-DD') + ' 00:00:00';
        stockForm["inventoryEndTime"] = stockForm.inventoryTime[1].format('yyyy-MM-DD') + ' 23:59:59';
        if (stockForm['dealerType'] && Object.is(stockForm['dealerType'], 'DISTRIBUTOR')) stockForm.parentName = stockForm.parentName.split(" ")[0];
        e.drawerBtnLoading()
        http
          .post(apis.saveCheckStockDetail, { ...stockForm, ...values })
          .then(res => {
            message.success('操作成功')
            e.close()
          })
          .catch(() => {
            e.drawerBtnLoadingHide()
          })
      } else {
        console.log(err)
      }
    })
  }

  //计算期间动销数
  private calcNowMove = () => {
    setTimeout(() => {
      let formValues = this.form.getFieldsValue()
      let beginningRealStock = formValues['beginningRealStock'] ?? null //期初库存
      let nowAog = formValues['nowAog'] ?? null //期间开单
      let allocateNumber = formValues['allocateNumber'] ?? null //调入调出
      let nowRealStock = formValues['nowRealStock'] ?? null //当前实物库存
      let onOrder = formValues['onOrder'] ?? null //当前未到货
      let nowMove = +beginningRealStock + +nowAog + +allocateNumber - +nowRealStock - +onOrder
      this.setState({ nowMove })
      this.form.setFieldsValue({ nowMove })
    }, 100)
  }

  private showMatName = () => {
    let formValues = this?.form?.getFieldsValue()
    return formValues && formValues['matName'] && `${formValues['matName'].matName || ""} ${formValues['matName'].prodBarcode || ""}`
  }

  // 添加物料盘点
  private handAddMaterialModal = () => {
    let { brandCode, dealerCode, inventoryTime } = this.stockForm
    UdModal.open({
      title: '添加盘点物料',
      width: '50%',
      content: (
        <AddMaterialModal
          inventoryBegineTime={inventoryTime[0].format('yyyy-MM-DD HH:mm:ss')}
          inventoryEndTime={inventoryTime[1].format('yyyy-MM-DD HH:mm:ss')}
          brandCode={brandCode}
          dealerCode={dealerCode}
        />
      ),
      onOk: value => {
        console.log('value', value)
        this.form.setFieldsValue({
          matName: value[0]
        })
      },
    })
  }

  render() {
    let { nowMove } = this.state
    let items: IUdFormItem[] = [
      { label: '销售组织', id: 'brandNameShort', render: () => <Input readOnly /> },
      { label: '客户名称', id: 'dealerName', render: () => <Input readOnly /> },
      { label: '盘点周期', id: 'description', render: () => <Input readOnly /> },
      {
        label: '物料描述',
        id: 'matName',
        rules: [validators.required],
        render: () => <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: '10px' }}>
          <Input readOnly value={this.showMatName()} />
          <UdToolbar
            other={
              <Button type="primary" onClick={this.handAddMaterialModal}>
                添加物料
              </Button>
            }
          ></UdToolbar>
        </div>
      },
      {
        label: '期初库存(含未到货)件',
        id: 'beginningRealStock',
        rules: [validators.required],
        render: () => <InputNumber onBlur={this.calcNowMove} precision={1} style={{ width: '100%' }} />,
      },
      {
        label: '期间开单/件',
        id: 'nowAog',
        rules: [validators.required],
        render: () => <InputNumber onBlur={this.calcNowMove} precision={1} style={{ width: '100%' }} />,
      },
      {
        label: '调入调出',
        id: 'allocateNumber',
        rules: [validators.required],
        render: () => <InputNumber onBlur={this.calcNowMove} precision={1} style={{ width: '100%' }} />,
      },
      {
        label: '当前实物库存/件',
        id: 'nowRealStock',
        rules: [validators.required],
        render: () => <InputNumber min={0} onBlur={this.calcNowMove} precision={1} style={{ width: '100%' }} />,
      },
      {
        label: '当前未到货/件',
        id: 'onOrder',
        rules: [validators.required],
        render: () => <InputNumber min={0} style={{ width: '100%' }} precision={1} onBlur={this.calcNowMove} />,
      },
      { label: '期间动销数/件', id: 'nowMove', render: () => <InputNumber readOnly style={{ width: '100%' }} /> },
      {
        label: '下月订单计划/件',
        id: 'nextMonthOrderNum',
        render: () => <InputNumber precision={1} style={{ width: '100%' }} />,
      },
      {
        label: '动销说明',
        id: 'nowMoveDes',
        rules: [nowMove !== null ? (nowMove < 0 ? validators.required : { required: false }) : { required: false }],
        render: <TextArea rows={3} />
      },
      { label: '备注信息', id: 'remark', render: <TextArea rows={3} /> },
    ]
    return (
      <>
        <UdForm
          labelCol={this.labelCol}
          wrapperCol={this.wrapperCol}
          getForm={form => (this.form = form)}
          items={items}
          values={this.stockForm}
        />
      </>
    )
  }
}
